package edu.hebeu.network;

import android.util.Log;

import org.json.JSONObject;

import java.io.IOException;
import java.util.Map;
import java.util.Set;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class API {

    private static API API_INSTANCE = new API();
    private static String API_URL; // 保存请求的url地址
    private static Map<String, Object> API_PARAMS; // 保存请求的参数列表
    private static OkHttpClient HTTP_CLIENT;
    private static String TOKEN;

    private API() {}

    /**
     * 这个方法用来配置请求API，如url地址，请求参数
     * @param url
     * @param params
     * @param token
     * @return
     */
    public static API requestConfig(String url, Map<String, Object> params, String token) {
        HTTP_CLIENT = new OkHttpClient.Builder().build();
        API_URL = APIConfig.BASE_URL + url;
        API_PARAMS = params;
        TOKEN = "Bearer " + token; // 对TOKEN在进行加工处理(让后台能够解析的形式而不是直接发送token内容)
        return API_INSTANCE;
    }

    /**
     * POST请求的方法
     * @param callback 回调
     */
    public void postRequest(final MyCallback callback, boolean isVer) {
        JSONObject json = new JSONObject(API_PARAMS); // 将参数列表转换成JSON格式
        String jsonStr = json.toString(); // 将JSON类型的数据转换成字符串
        RequestBody requestBody = RequestBody.create(
                MediaType.parse("application/json;charset=utf-8"), jsonStr); // 通过JSON字符串设置请求体的内容
        // 创建Request请求对象
        Request request = null;
        if (isVer) { // 如果是需要身份验证的并且TOKEN有值
            request = new Request.Builder().url(API_URL)
                .addHeader("contentType", "application/json;charset=utf-8")
                .addHeader("authorization", TOKEN)
                .post(requestBody)
                .build();
        } else { // 否则即不需要身份验证
            request = new Request.Builder().url(API_URL)
                .addHeader("contentType", "application/json;charset=utf-8")
                .post(requestBody)
                .build();
        }
        // 创建Call对象
        final Call call = HTTP_CLIENT.newCall(request);
        // 发起请求
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("请求失败！", e.getMessage());
                callback.onFailure(e); // 调用传入的CallBack对象的onFailure()方法
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String result = response.body().string();
                callback.onSuccess(result); // 调用传入的Callback对象的onSuccess()方法
            }
        });
    }

    public void getRequest(final MyCallback callback, boolean isVer) {
        Set<Map.Entry<String, Object>> params = API_PARAMS.entrySet();
        int i = 1;
        for (Map.Entry<String, Object> param : params) { // 拼接GET请求的参数
            if (i == 1) { // 如果是第一个参数
                API_URL += "?" + param;
            } else { // 否则，即是第二个参数
                API_URL += "&" + param;
            }
            i++;
        }
        Request request = null;
        if (isVer) { // 如果是需要身份验证的
            request = new Request.Builder().url(API_URL)
                .addHeader("authorization", TOKEN)
                .get()
                .build();
        } else { // 否则即不需要身份验证
            request = new Request.Builder().url(API_URL)
                .get()
                .build();
        }

        Call call = HTTP_CLIENT.newCall(request);
        // 发起请求
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("请求失败！", e.getMessage());
                callback.onFailure(e); // 调用传入的CallBack对象的onFailure()方法
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String result = response.body().string();
                callback.onSuccess(result); // 调用传入的Callback对象的onSuccess()方法
            }
        });
    }
}
